package com.t2t.top.framework.diamond;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

/**
 * Created by yangpengfei on 2016/8/22.
 */
public class PropertiesLoader {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String SUFFIX_PROPERTIES = ".properties";

    private static final String DEFAULT_RESOURCE_ENV = "env.properties";

    private static final String DEFAULT_RESOURCE_ENV_EXT = "META-INF/env";

    public Properties mergeProperties() {
        Properties result = new Properties();
        List<Properties> propertiesList = loadProperties();
        for (Properties localProp : propertiesList) {
            CollectionUtils.mergePropertiesIntoMap(localProp, result);
        }
        return result;
    }

    public List<Properties> loadProperties() {
        List<Properties> properties = new ArrayList<Properties>();
        try {
            ClassLoader classLoader = new PropertiesLoader().getClass().getClassLoader();
            Enumeration<URL> urls = classLoader.getResources(DEFAULT_RESOURCE_ENV_EXT);
            ArrayList<File> files = new ArrayList();
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                findFiles(url.getPath(), files);
            }

            files.add(new File(classLoader.getResource(DEFAULT_RESOURCE_ENV).getFile()));

            properties = findPropertieFiles(files);
            return properties;
        } catch (Exception e) {
            logger.error("配置文件读取失败", e);
        }
        return properties;
    }

    public void findFiles(String path, ArrayList<File> fileName) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                findFiles(f.getAbsolutePath(), fileName);
            } else {
                fileName.add(f);
            }
        }
    }

    private List<Properties> findPropertieFiles(List<File> files) {
        List<Properties> properties = new ArrayList();
        for (File file : files) {
            if (file.getName().endsWith(SUFFIX_PROPERTIES)) {
                try {
                    properties.add(PropertiesUtils.toProperties(new FileInputStream(file)));
                } catch (FileNotFoundException e) {
                    logger.error("文件不存在:{}", file.getAbsolutePath());
                    logger.error("读取失败", e);
                }
            }
        }
        return properties;
    }


}
